﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace Urbania.Utilities
{
    public class Animation
    {
        public Texture2D SpriteSheet { get; set; }
        public int FrameWidth { get; set; }
        public int FrameHeight { get; set; }
        public int NumberOfFrames { get { return SpriteSheet.Width / FrameWidth; } }

        private bool _isrunning;
        public bool IsRunning
        {
            get
            {
                return _isrunning;
            }
            set
            {
                _isrunning = value;
                elapsedTime= 0; //Reset the timer
            }
        }
        public bool Reverse { get; set; }

        public int FrameIndex { get; set; }

        public int RepeatFrameIndex { get; set; }

        public Rectangle CurrentFrameBounds
        {
            get
            {
                return new Rectangle(FrameIndex * FrameWidth, 0, FrameWidth, FrameHeight);
            }
        }

        private float _frameRate;
        /// <summary>
        /// The framerate in frames per second
        /// </summary>
        public float FrameRate {
            get
            {
                return _frameRate;
            }
            set
            {
                _frameRate = value;
            }
        }
        /// <summary>
        /// The period in milliseconds
        /// </summary>
        public float Period 
        {
            get
            {
                return 1000.0f * (1 / _frameRate);
            }
            set
            {
                _frameRate = 1 / (value * 1000f);
            }
        }


        private long elapsedTime = 0;

        public void Update(GameTime gt)
        {
            if (!IsRunning) return;
            elapsedTime += gt.ElapsedGameTime.Milliseconds;
            if (elapsedTime >= Period)
            {
                if (!Reverse) NextFrame();
                else PreviousFrame();
                elapsedTime = 0;
            }
        }

        public void NextFrame()
        {
            this.FrameIndex = (++this.FrameIndex+NumberOfFrames) % NumberOfFrames;
            if (FrameIndex < RepeatFrameIndex)
            {
                FrameIndex = RepeatFrameIndex;
            }
        }
        public void PreviousFrame()
        {
            this.FrameIndex = (--this.FrameIndex + NumberOfFrames) % NumberOfFrames;
            if (FrameIndex < RepeatFrameIndex)
            {
                FrameIndex = NumberOfFrames - 1;
            }
        }

    }
}
